package shuanfa;

import java.util.ArrayList;
import java.util.Scanner;

/**
 * 顺时针打印矩阵
 */
public class PrintMatrixClockwisely {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int cols = scanner.nextInt();
        int rows = scanner.nextInt();
        int k = 0;
        int[][] nums = new int[cols][rows];
        for (int i = 0; i < cols; i++) {
            for (int j = 0; j < rows; j++) {
                nums[i][j] = scanner.nextInt();
            }
        }
        for (int i = 0; i < nums.length; i++) {
            for (int j = 0; j < nums[0].length; j++) {
                System.out.print(nums[i][j] + "\t");
            }
            System.out.println();
        }
        ArrayList<Integer> list = printMatrixClockwisely(nums);
        System.out.println(list.toString());
    }

    public static ArrayList<Integer> printMatrixClockwisely(int[][] nums) {
        ArrayList<Integer> list = new ArrayList<>();
        int cols = nums.length;
        int rows = nums[0].length;
        if (nums == null || cols <= 0 || rows <= 0) {
            return null;
        }
        int start = 0;
        while (cols > start * 2 && rows > start * 2) {
            printMatrixInCircle(list, nums, cols, rows, start);
            start++;
        }
        return list;
    }

    private static void printMatrixInCircle(ArrayList<Integer> list, int[][] nums,
                                            int cols, int rows, int start) {
        int endX = cols - 1 - start;
        int endY = rows - 1 - start;
        //从左到右打印一行
        for (int i = start; i <= endX; i++) {
            int number = nums[start][i];
            list.add(number);
        }
        //从上往下打印一列
        if (start < endY) {
            for (int i = start + 1; i <= endY; i++) {
                int number = nums[i][endX];
                list.add(number);
            }
        }
        //从右向左打印一行
        if (start < endX && start < endY) {
            for (int i = endX - 1; i >= start; i--) {
                int number = nums[endY][i];
                list.add(number);
            }
        }
        //重下往上打印一列
        if (start < endY && start < endX) {
            for (int i = endY - 1; i > start; i--) {
                int number = nums[i][start];
                list.add(number);
            }
        }
    }
}
